package com.rex.saas.mqtt;

import com.rex.saas.utils.MacAddressUtil;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

/**
 * 项目启动 订阅主题
 *
 * @author zhusiyu
 */
@Slf4j
@Component
@Getter
public class MaMqttManager implements ApplicationRunner {

    @Resource
    private MaListenerCallback maListenerCallback;

    @Resource
    private MaMqttConnect maMqttConnect;

    @Value("${maMqtt.clientId}")
    private String maClientId;

    @Value("${maMqtt.username}")
    private String maUserName;

    @Value("${maMqtt.password}")
    private String maPassword;

    @Override
    public void run(ApplicationArguments args) {
        String macAddress = MacAddressUtil.getMacAddress();
        if (StringUtils.isEmpty(maClientId)){
            maClientId = "GW_"+macAddress;
        }
        if (StringUtils.isEmpty(maUserName)){
            maUserName = macAddress;
        }
        if (StringUtils.isEmpty(maPassword)){
            maPassword = macAddress;
        }
        try {
            maMqttConnect.setMqttClient("GW_"+macAddress, maUserName, maPassword, maListenerCallback);
            maMqttConnect.sub("/paas/"+macAddress+"/down");

        } catch (Exception e) {
            log.error("MQTT启动连接失败！macAddress:{}", macAddress, e);
        }
    }
}
